﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Diagnostics;
using System.IO;
using System.Timers;
using XYAC.Framework.WohuaMesExtend.IHI.Extensions;
using XYAC.Framework.WohuaMesExtend.IHI.LocalData.Context;
using XYAC.Framework.WohuaMesExtend.IHI.Services;

namespace XYAC.Framework.WohuaMesExtend.IHI.ViewModels
{
    /// <summary>
    /// 在此类中，实现了向MES中间表传递数据。
    /// </summary>
    public partial class MainWindowViewModel : ViewModelBase
    {
        public MainWindowViewModel(ILogger<MainWindowViewModel> _logger, QualityDataHistoryViewModel model, IServiceProvider serviceProvider)
        {
            var options = serviceProvider.GetService<IOptionsMonitor<AppConfig>>();
            this.Logger = _logger;
            this.Model = model;
            this.ServiceProvider = serviceProvider;
            this.AppConfig = options;
            InitializeTask();
        }

        public System.Timers.Timer ProduceDataUploaderTimer { get; private set; }
        public ILogger<MainWindowViewModel> Logger { get; }
        public QualityDataHistoryViewModel Model { get; }
        public IServiceProvider ServiceProvider { get; }
        public IOptionsMonitor<AppConfig> AppConfig { get; }
        public System.Timers.Timer LogCleaner { get; private set; }
        public System.Timers.Timer DataRefreshTimer { get; private set; }
        public DateTime LastCreateNextDbDate { get; private set; } = DateTime.MinValue.Date;

        private void InitializeTask()
        {
            LogCleaner = new System.Timers.Timer();
            LogCleaner.Elapsed += LogCleaner_Elapsed;
            LogCleaner.Interval = 1 * 60 * 1000;//60秒
            LogCleaner.Start();


            //生产数据同步,FirstTime
            ProduceDataUploaderTimer = new System.Timers.Timer();
            ProduceDataUploaderTimer.Elapsed += ProduceDataUploaderTimer_Elapsed;


            ProduceDataUploaderTimer.Interval = 1 * 60 * 1000;//60秒
            ProduceDataUploaderTimer.Start();


            DataRefreshTimer = new System.Timers.Timer();
            DataRefreshTimer.Elapsed += DataRefreshTimer_Elapsed;
            DataRefreshTimer.Interval = 5 * 1000;//60秒
            DataRefreshTimer.Start();


            Task.Run(() =>
            {
                ProduceDataUploaderTimer_Elapsed(null, null);
            });
        }

        private void DataRefreshTimer_Elapsed(object? sender, ElapsedEventArgs e)
        {
            Model.QueryLocalDataHistory();
        }

        private void LogCleaner_Elapsed(object? sender, ElapsedEventArgs e)
        {
            try
            {
                #region 清理日志
                var directoryInfo = new DirectoryInfo("./log");
                var files = directoryInfo.GetFiles("*");
                foreach (var file in files)
                {
                    if (file.LastWriteTime < DateTime.Now.AddMonths(-1))
                    {
                        try
                        {
                            file.Delete();
                        }
                        catch
                        {

                        }
                    }
                }
                #endregion


                var createDbFlag = false;
                var isDeleted = false;
                //定期检查创建次日数据库
                using (var scope = this.ServiceProvider.CreateScope())
                {
                    try
                    {
                        if (LastCreateNextDbDate < DateTime.Now.Date)
                        {
                            var context = scope.ServiceProvider.GetService<LocalTomorrowDataContext>();
                            //数据库文件是否存在
                            var fileDbFileExists = context.GetDbFileCreated();
                            if (fileDbFileExists)
                                isDeleted = context.Database.EnsureDeleted();

                            if (!fileDbFileExists || isDeleted)
                            {
                                createDbFlag = context.Database.EnsureCreated();
                                if (createDbFlag)
                                {
                                    LastCreateNextDbDate = DateTime.Now.Date;
                                }
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        Logger?.LogError("检测到次日数据库无法连接", ex);
                    }
                }
            }
            catch (Exception)
            {

            }

            try
            {
                var directoryInfo = new DirectoryInfo("./LocalDB");
                var files = directoryInfo.GetFiles("*.sqlite");
                foreach (var file in files)
                {
                    if (file.LastWriteTime < DateTime.Now.AddMonths(-1))
                    {
                        try
                        {
                            file.Delete();
                        }
                        catch
                        {

                        }
                    }
                }
            }
            catch (Exception)
            {

            }

        }


        private static readonly SemaphoreSlim uploadSemaphore = new SemaphoreSlim(1, 1);
        private static readonly SemaphoreSlim syncAppDataSemaphore = new SemaphoreSlim(1, 1);
        private static readonly SemaphoreSlim localSyncSemaphore = new SemaphoreSlim(1, 1);

        /// <summary>
        /// 定期上传生产数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProduceDataUploaderTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            // 尝试同步地获取信号量，不等待
            bool lockAcquired = uploadSemaphore.Wait(0);
            if (!lockAcquired)
            {
                Logger?.LogWarning("同步任务已在运行，跳过此次调用。");
                return;
            }
            try
            {
                using (var scope = ServiceProvider.CreateScope())
                {
                    var mesService = scope.ServiceProvider.GetService<YB_PROCESS_STEPService>();
                    //var ct = scope.ServiceProvider.GetService<DataContext.AccessIHIDbContext>();

                    //var ctYst = scope.ServiceProvider.GetService<DataContext.AccessIHIDbContext>();
                    var localDbSyncService = scope.ServiceProvider.GetService<LocalDataService>();

                    //同步Access数据库差异到本地记录
                    var ret = localDbSyncService?.SyncNewData();

                    //以下用于检测未同步数据并上传
                    var syncCount = 0;
                    do
                    {
                        try
                        {
                            using (var localDbService = scope.ServiceProvider.GetService<LocalDataService>())
                            {

                                syncCount = localDbService.UploadData();
                                var msg = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}UploadYesterdayData:今日数据同步数量:{syncCount}";
                                Debug.WriteLine(msg);
                                Logger?.LogInformation(msg);
                            }
                        }
                        catch (Exception)
                        {
                            break;
                        }
                    } while (syncCount > 0);//同步本日数据
                    do
                    {
                        try
                        {
                            using (var localDbService = scope.ServiceProvider.GetService<LocalDataService>())
                            {
                                syncCount = localDbService.UploadYesterdayData();
                                var msg = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}UploadYesterdayData:昨日数据同步数量:{syncCount}";
                                Debug.WriteLine(msg);
                                Logger?.LogInformation(msg);
                            }
                        }
                        catch (Exception)
                        {
                            break;
                        }
                    } while (syncCount > 0);//同步昨日数据


                }
                uploadSemaphore.Release();
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"ProduceDataUploaderTimer_Elapsed:定期上传生产数据发生异常:{ex.Message}");
                Logger?.LogError($"定期上传生产数据发生异常:{ex.Message}{ex.StackTrace}", ex);

                uploadSemaphore.Release();
            }
            finally
            {

                //此处刷新数据
                Model.QueryLocalDataHistory();
            }
        }
    }


}
